<script lang="ts">
    import { useDatepickerContext } from "./Datepicker.svelte";
    import { clearHms, isBetween, sameDate, sameMonth } from "./utils";

    const props = $props();
    const ctx: any = useDatepickerContext();
    const today = clearHms(new Date());
    const isToday = props.day ? today.toLocaleDateString() === props.day.toLocaleDateString() : false;
    const isActive = $derived(
        props.type === "dateRange" || props.type === "dateTimeRange"
            ? false
            : props.value && props.value instanceof Date && props.day
              ? props.value.toLocaleDateString() === props.day.toLocaleDateString()
              : false
    );
    let disabled = props.day && ctx && ctx.disabledDate && ctx.disabledDate(props.day);
    if (!(props.month && props.day && sameMonth(props.month, props.day))) {
        disabled = true;
    }
    const inRange = $derived(props.range && props.day ? isBetween(props.range, props.day) : false);
    const firstRange = $derived(props.range && props.range[0] && props.day && sameDate(props.range[0], props.day));
    const lastRange = $derived(props.range && props.range[1] && props.day && sameDate(props.range[1], props.day));
    const inHover = $derived.by(() => {
        const hoverDate = props.range && props.range.length === 1 && props.hoverDate ? [props.hoverDate, props.range[0]] : [];
        hoverDate.length === 2 &&
            hoverDate.sort((a, b) => {
                return a.getTime() - b.getTime();
            });
        return hoverDate && props.day ? isBetween(hoverDate, props.day) : false;
    });
    const classList = $derived.by(() => {
        const obj = {
            "cm-date-picker-day": true,
            "cm-date-picker-empty": !props.day,
            "cm-date-picker-today": isToday,
            "cm-date-picker-active": isActive,
            "cm-date-picker-inrange": !disabled && inRange,
            "cm-date-picker-inhover": !disabled && inHover,
            "cm-date-picker-first-range": firstRange,
            "cm-date-picker-last-range": lastRange,
            "cm-date-picker-day-disabled": disabled,
        };
        return obj;
    });

    const onDayClick = () => {
        if (props.day) {
            ctx && ctx.onSelectDate(props.day, props.name);
        }
    };

    const onMouseOver = () => {
        if (props.day) {
            ctx && ctx.onMouseOver(props.day);
        }
    };
</script>

<!-- svelte-ignore a11y_no_static_element_interactions -->
<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_mouse_events_have_key_events -->
<div class={classList} onclick={onDayClick} onmouseover={onMouseOver}>
    <em>{props.day ? props.day.getDate() : ""}</em>
</div>
